package br.com.searchpeople.activity;

import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import br.com.searchpeople.R;
import br.com.searchpeople.database.SingletonPostBD;
import br.com.searchpeople.model.PostModel;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapActivity extends Activity {

	// Google Map
	private GoogleMap googleMap;
	private List<PostModel> postsList;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_map);

		try {
			// Loading map
			initilizeMap();

			// Changing map type
			googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

			double latitude;
			double longitude;
			postsList = SingletonPostBD.getInstance(getApplicationContext()).getAllPosts(); 
			int n = postsList.size();
			for (int i = 0; i < n; i++) {
				latitude = postsList.get(i).getLatitude();
				longitude = postsList.get(i).getLongitude();
				// Adding a marker to each people
				MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title(postsList.get(i).getName());
				googleMap.addMarker(marker);

				// Move the camera to last position with a zoom level
				CameraPosition cameraPosition = new CameraPosition.Builder()
							.target(new LatLng(latitude,longitude)).zoom(9).build();

				googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
				
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@Override
	protected void onResume() {
		super.onResume();
		initilizeMap();
	}

	/**
	 * function to load map If map is not created it will create it for you
	 * */
	private void initilizeMap() {

		Log.d("Debug maps", "initializeMap");
		if (googleMap == null) {
			googleMap = ((MapFragment) getFragmentManager().findFragmentById(
					R.id.map)).getMap();

			// check if map is created successfully or not
			if (googleMap == null) {
				Toast.makeText(getApplicationContext(),
						"Sorry! unable to create maps", Toast.LENGTH_SHORT)
						.show();
			}
		}
	}
}
